import JsEncrypt from 'jsencrypt';
import CryptoJS from 'crypto-js';

/**
 * @des: 随机数
*/
export const AESKey = () => {
  const len = 16;
  const $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  const maxPos = $chars.length;
  let pwd = '';
  for (let i = 0; i < len; i += 1) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }

  return pwd;
};

/**
 * @des: AES
*/
const iv = CryptoJS.enc.Utf8.parse('4C29A844B880FDF3');

/*
 * @Description: RSA 公钥加密
*/
export const RSAEncrypt = (pwd) => {
  const pubKey = `-----BEGIN  PUBLIC  KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMEUdXHUR/TALB4WL1LiGWQ2Cv
  UgIronEX8GT/5siKOopB42mM6D2NIiZeRVq33ST+o2aQQOhvtCnhOS2judUOtCCr
  kZ8p77e1qGY2Z2zr9Jt3P/6NmtuTQXBuFDCT4xcsXI3Ftv3da9swqsrU3tdq7A3M
  7MNIpRj9QbtTSTkXmQIDAQAB
  -----END  PUBLIC  KEY-----`;

  const Jse = new JsEncrypt();
  Jse.setPublicKey(pubKey);
  return Jse.encrypt(pwd);
};

/*
 * @Description: RSA 私钥解密
*/
export const RsaDecrypt = (pwd) => {
  const priKey = '私钥';

  const Jse = new JsEncrypt();
  Jse.setPrivateKey(priKey);
  return Jse.decrypt(pwd);
};

/**
 * des: AES 加密
 * @param parameter
 * @returns {*}
*/
export const AESEncrypt = (word, Key) => {
  const key = CryptoJS.enc.Utf8.parse(Key);
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  return encrypted.toString();
};

/**
 * des: AES 解密
 * @param parameter
 * @returns {*}
*/
export const AESDecrypt = (word, Key) => {
  const key = CryptoJS.enc.Utf8.parse(Key);
  const decrypt = CryptoJS.AES.decrypt(word, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
};
